<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px"
             >
      <el-form-item label="患者来源" prop="source">
        <el-select v-model="queryParams.source" placeholder="请选择患者来源" clearable>
          <el-option
            v-for="dict in dict.type.patient_source"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="病种" prop="disease">
        <el-select v-model="queryParams.disease" placeholder="请选择患者所在病种" clearable>
          <el-option
            v-for="dict in dict.type.disease"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="科室" prop="department">
        <el-select v-model="queryParams.department" placeholder="请选择患者所在科室" clearable>
          <el-option
            v-for="dict in dict.type.department"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="病区" prop="ward">
        <el-select v-model="queryParams.ward" placeholder="请选择患者所在病区" clearable>
          <el-option
            v-for="dict in dict.type.ward"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
        <!--        <el-input-->
        <!--          v-model="queryParams.ward"-->
        <!--          placeholder="请输入病区"-->
        <!--          clearable-->
        <!--          @keyup.enter.native="handleQuery"-->
        <!--        />-->
      </el-form-item>
      <!--      <el-form-item label="就诊状态" prop="status">-->
      <!--        <el-select v-model="queryParams.status" placeholder="请选择就诊状态" clearable>-->
      <!--          <el-option-->
      <!--            v-for="dict in dict.type.clinic_status"-->
      <!--            :key="dict.value"-->
      <!--            :label="dict.label"-->
      <!--            :value="dict.value"-->
      <!--          />-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <!--        <el-button-->
        <!--          type="danger"-->
        <!--          plain-->
        <!--          icon="el-icon-delete"-->
        <!--          size="mini"-->
        <!--          :disabled="multiple"-->
        <!--          @click="handleDelete"-->
        <!--          v-hasPermi="['system:clinic:remove']"-->
        <!--        >删除-->
        <!--        </el-button>-->
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出
        </el-button>
        <el-button
          size="mini"
          icon="el-icon-s-data"
          @click="getList()"
          v-hasPermi="['system:clinic:remove']"
        >显示全部就诊记录
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getListbyone"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="clinicList" @selection-change="handleSelectionChange" :default-sort = "{prop: 'clinicId', order: 'descending'}">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" type="index" width="50"/>
<!--      <el-table-column label="就诊编号" align="center" prop="clinicId" sortable/>-->
      <el-table-column label="患者编号" align="center" prop="patientNo" sortable/>
      <el-table-column label="患者名称" align="center" prop="patientName">
        <template slot-scope="scope">
          <router-link :to="{name:'patient_detail',params:{patientId:scope.row.patientId}}" class="link-type">
            <span>{{ scope.row.patientName }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column label="年龄" align="center" prop="patientAge"/>
      <el-table-column label="诊断" align="center" prop="preDiagnose"/>
      <el-table-column label="病情摘要" align="center" prop="illnessSummary"/>
      <el-table-column label="科室" align="center" prop="department">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.department!==null">
            <dict-tag :options="dict.type.department" :value="scope.row.department"/>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="病区" align="center" prop="ward">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.ward!==null">
            <dict-tag :options="dict.type.ward" :value="scope.row.ward"/>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="病种" align="center" prop="disease">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.disease!==null">
            <dict-tag :options="dict.type.disease" :value="scope.row.disease"/>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否在院" align="center" prop="patientStatus">
        <template slot-scope="scope">
          <el-switch
            :value="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>

      <el-table-column style="min-width: 50px" label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <router-link :to="'/gaoxin/taskdata-task/add/' + scope.row.clinicId" class="link-type">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
            >分配
            </el-button>
          </router-link>
          <!--          <el-button-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-delete"-->
          <!--            @click="handleDelete(scope.row)"-->
          <!--            v-hasPermi="['system:clinic:remove']"-->
          <!--          >删除-->
          <!--          </el-button>-->
          <br>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-order"
            @click="totasks(scope.row)"
          >查看相关任务
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getListbyone"
    />

    <!-- 患者列表弹窗 -->
    <el-dialog :title="patientTitle" :visible.sync="vis" width="70%" append-to-body>
      <el-form :model="queryPatientParams" ref="queryPatientParams" size="small" :inline="true"
               v-show="showSearch"
               label-width="auto" label-position="right">
        <el-form-item label="患者编号" prop="patientNo">
          <el-input
            v-model="queryPatientParams.patientNo"
            placeholder="请输入患者编号"
            clearable
            @keyup.enter.native="patientQuery"
          />
        </el-form-item>
        <el-form-item label="患者名称" prop="patientName">
          <el-input
            v-model="queryPatientParams.patientName"
            placeholder="请输入患者名称"
            clearable
            @keyup.enter.native="patientQuery"
          />
        </el-form-item>
        <el-form-item label="身份证号" prop="patientIdentityNo">
          <el-input
            v-model="queryPatientParams.patientIdentityNo"
            placeholder="请输入患者身份证号"
            clearable
            @keyup.enter.native="patientQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="patientQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="patientResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="patientList" @selection-change="handleSelectionChange" :default-sort = "{prop: 'patientNo', order: 'descending'}">
<!--        <el-table-column type="selection" width="55" align="center"/>-->
        <el-table-column label="患者编号" align="center" prop="patientNo" sortable/>
        <el-table-column label="患者名称" align="center" prop="patientName" />
        <el-table-column label="患者年龄" align="center" prop="patientAge"/>
        <el-table-column label="患者性别" align="center" prop="patientGender">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.patientGender"/>
          </template>
        </el-table-column>
        <el-table-column label="患者状态" align="center" prop="patientStatus">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.patient_status" :value="scope.row.patientStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleSelect(scope.row)"
            >选择
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryPatientParams.pageNum"
        :limit.sync="queryPatientParams.pageSize"
        @pagination="getPatientList"
      />
    </el-dialog>


    <!-- 添加或修改就诊信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" :close-on-click-modal="false" width="70%" append-to-body>
      <el-tabs type="border-card" v-model="activeName"  @tab-click="handleClick">

        <el-tab-pane name="1" label="基本信息">
          <el-form ref="patientForm" :rules="patientrules" :model="patientForm" label-width="100px" label-position="top">
            <el-row :gutter="10">
              <el-row :gutter="10">
                <el-col :span="12">
                  <el-form-item label="身份证号" prop="patientIdentityNo">
                    <el-input v-model="patientForm.patientIdentityNo" placeholder="请输入患者身份证号" maxlength="18"/>
                    <!--                    <el-button @click="importpat">导入数据</el-button>-->
                  </el-form-item>
                </el-col>
                <el-col :span="8" :offset="4">
                  <el-form-item label="患者编号(只读)" prop="patientNo">
                    <el-input v-model="patientForm.patientNo" placeholder="" readonly/>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="8">
                  <el-form-item label="患者名称" prop="patientName">
                    <el-input v-model="patientForm.patientName" placeholder="请输入患者名称" maxlength="10"/>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="患者生日" prop="patientBirthday">
                    <el-date-picker clearable
                                    v-model="patientForm.patientBirthday"
                                    type="date"
                                    value-format="yyyy-MM-dd"
                                    placeholder="请选择患者生日">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="患者年龄" prop="patientAge">
                    <el-input v-model="patientForm.patientAge" placeholder="请输入患者年龄"/>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="8">
                  <el-form-item label="患者性别" prop="patientGender">
                    <el-select v-model="patientForm.patientGender" placeholder="请选择患者性别" clearable>
                      <el-option
                        v-for="dict in dict.type.sys_user_sex"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                    <!--                    <el-input v-model="patientForm.patientGender" placeholder="请输入患者性别"/>-->
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="患者身高" prop="patientHeight">
                    <el-input v-model="patientForm.patientHeight" placeholder="请输入患者身高" maxlength="3">
                      <i slot="append">cm</i>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="患者体重" prop="patientWeight">
                    <el-input v-model="patientForm.patientWeight" placeholder="请输入患者体重" maxlength="3">
                      <i slot="append">kg</i>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="8">
                  <el-form-item label="患者民族" prop="patientFolk">
                    <el-input v-model="patientForm.patientFolk" placeholder="请输入患者民族" maxlength="10"/>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="患者职业" prop="patientJob">
                    <el-input v-model="patientForm.patientJob" placeholder="请输入患者职业" maxlength="10"/>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="婚姻状态" prop="patientMarriage">
                    <el-select v-model="patientForm.patientMarriage" placeholder="请选择患者状态" clearable>
                      <el-option
                        v-for="dict in dict.type.marital_status"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                    <!--                    <el-input v-model="patientForm.patientMarriage" placeholder="请输入婚姻状态"/>-->
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="12">
                  <el-form-item label="患者地址" prop="patientAddress">
                    <el-input v-model="patientForm.patientAddress" placeholder="请输入患者地址" maxlength="30"/>
                  </el-form-item>
                </el-col>
                <el-col :span="8" :offset="4">
                  <el-form-item label="联系方式" prop="patientPhone">
                    <el-input v-model="patientForm.patientPhone" placeholder="请输入联系方式" maxlength="11"/>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-row>
          </el-form>
        </el-tab-pane>

<!--        <el-tab-pane name="2">-->
<!--          <div slot="label" >就诊信息1</div>-->
<!--        </el-tab-pane>-->

        <el-tab-pane name="2" label="就诊信息">
          <el-form ref="form" :rules="clinicrules" :model="form" label-width="100px" label-position="top">
            <el-row :gutter="10">
              <el-col :span="8">
                <el-form-item label="患者来源" prop="source">
                  <template>
                    <el-radio-group v-model="form.source">
                      <el-radio :label="0">门诊</el-radio>
                      <el-radio :label="1">住院</el-radio>
                    </el-radio-group>
                  </template>
<!--                  <el-select v-model="form.source" placeholder="请选择患者来源" clearable>-->
<!--                    <el-option-->
<!--                      v-for="dict in dict.type.patient_source"-->
<!--                      :key="dict.value"-->
<!--                      :label="dict.label"-->
<!--                      :value="dict.value"-->
<!--                    />-->
<!--                  </el-select>-->
                  <!--                  <el-input v-model="form.source" placeholder="请输入患者来源"/>-->
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="6">
                <el-form-item label="病种" prop="disease">
                  <el-select v-model="form.disease" placeholder="请选择患者病种" clearable>
                    <el-option
                      v-for="dict in dict.type.disease"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                  <!--                  <el-input v-model="form.disease" placeholder="请输入病种"/>-->
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="科室" prop="department">
                  <el-select v-model="form.department" placeholder="请选择患者科室" clearable>
                    <el-option
                      v-for="dict in dict.type.department"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                  <!--                  <el-input v-model="form.department" placeholder="请输入科室"/>-->
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="病区" prop="ward">
                  <el-select v-model="form.ward" placeholder="请选择患者病区" clearable>
                    <el-option
                      v-for="dict in dict.type.ward"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                  <!--                  <el-input v-model="form.ward" placeholder="请输入病区"/>-->
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="病床" prop="bedNum">
                  <el-input v-model="form.bedNum" placeholder="请输入病床"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="24">
                <el-form-item label="诊断" prop="preDiagnose">
                  <el-input v-model="form.preDiagnose" type="textarea" placeholder="请输入内容"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="8">
                <el-form-item label="接诊医生/管床医生姓名" prop="manageId">
<!--                  <el-input v-model="form.manageId" placeholder="请输入接诊医生/管床医生编码"/>-->
                  <el-select v-model="form.manageId" placeholder="请选择接诊医生/管床医生姓名" style="width: 100%;">
                    <el-option
                      v-for="item in userOptions"
                      :key="item.userId"
                      :label="item.nickName"
                      :value="item.userId"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="一线医生姓名" prop="firstDoctorId">
<!--                  <el-input v-model="form.firstDoctorId" placeholder="请输入一线医生编码"/>-->
                  <el-select v-model="form.firstDoctorId" placeholder="请选择一线医生姓名" style="width: 100%;">
                    <el-option
                      v-for="item in userOptions"
                      :key="item.userId"
                      :label="item.nickName"
                      :value="item.userId"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="二线医生姓名" prop="secondDoctorId">
<!--                  <el-input v-model="form.secondDoctorId" placeholder="请输入二线医生编码"/>-->
                  <el-select v-model="form.secondDoctorId" placeholder="请选择二线医生姓名" style="width: 100%;">
                    <el-option
                      v-for="item in userOptions"
                      :key="item.userId"
                      :label="item.nickName"
                      :value="item.userId"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="24">
                <el-form-item label="病情摘要" prop="illnessSummary">
                  <el-input v-model="form.illnessSummary" type="textarea" placeholder="请输入内容"/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="既往史" prop="preHistory">
                  <el-input v-model="form.preHistory" type="textarea" placeholder="请输入既往史"/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="家族史" prop="familyHistory">
                  <el-input v-model="form.familyHistory" type="textarea" placeholder="请输入家族史"/>
                </el-form-item>
              </el-col>
            </el-row>
            <!--            <el-form-item label="患者主索引" prop="patientId">-->
            <!--              <el-input v-model="form.patientId" placeholder="请输入患者主索引"/>-->
            <!--            </el-form-item>-->
          </el-form>
        </el-tab-pane>

      </el-tabs>

      <div slot="footer" class="dialog-footer">
        <div style="float: left">
          <el-button type="primary" @click="getPatientList">患者列表</el-button>
          <el-button type="primary" @click="handleOCR">文字识别</el-button>
          <el-button type="primary" @click="handleSpeech">语音识别</el-button>
        </div>
        <el-button type="primary" icon="el-icon-arrow-left" v-show="(activeName=='2')" @click="charge1">上一页</el-button>
        <el-button type="primary" v-show="(activeName=='1')" @click="charge2">下一页<i class="el-icon-arrow-right el-icon--right"></i></el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>

    </el-dialog>

    <el-dialog
      title="文字识别"
      :visible.sync="open0"
      width="50%"
      :before-close="handleClose">

      <el-upload ref="upload"
                 action="action"
                 :show-file-list="false"
                 :http-request="uploadFile">
        <el-button type="primary">上传图片</el-button>
      </el-upload>
      <div
        v-loading="vloading"
        element-loading-text="文字识别中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)">
        <el-input
          class="inputArea"
          type="textarea"
          :rows="5"
          placeholder="请先上传要识别的图片"
          v-model="ocrsen"
          style="margin-top: 20px">
        </el-input>
      </div>
      <span slot="footer" class="dialog-footer">
      <el-button @click="cancelDialog">取 消</el-button>
     </span>
    </el-dialog>

    <el-dialog
      title="语音识别"
      :visible.sync="open1"
      width="50%"
      :before-close="handleClose">
      <div class="Asr">
        <br/>
        <h3>录音时长：{{ recorder && recorder.duration.toFixed(4) }}</h3>
        <el-button type="primary" @click="startRecorder()">开始录音</el-button>
        <el-button type="primary" @click="pauseRecorder()">暂停录音</el-button>
        <el-button type="primary" @click="resumeRecorder()">继续录音</el-button>
        <el-button type="primary" @click="stopRecorder()">结束录音</el-button>
        <br/>
        <h3>
          播放时长：{{
            recorder &&
            (playTime > recorder.duration
              ? recorder.duration.toFixed(4)
              : playTime.toFixed(4))
          }}
        </h3>
        <el-button type="success" @click="playRecorder()">录音播放</el-button>
        <el-button type="success" @click="pausePlayRecorder()">暂停播放</el-button>
        <el-button type="success" @click="resumePlayRecorder()">恢复播放</el-button>
        <el-button type="success" @click="stopPlayRecorder()">停止播放</el-button>
        <br/>
        <br/>
        <el-button type="success" @click="asrRecorder()">上传识别</el-button>
        <el-button type="info" @click="destroyRecorder()">销毁录音</el-button>
        <el-button type="info" @click="asrsen = ''">清空内容</el-button>
        <div
          v-loading="vloading"
          element-loading-text="语音识别中"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.8)">
          <el-input
            class="inputArea"
            type="textarea"
            :rows="5"
            placeholder="请先录制要识别的音频"
            v-model="asrsen"
            style="margin-top: 20px">
          </el-input>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
      <el-button @click="cancelDialog">取 消</el-button>
     </span>
    </el-dialog>

  </div>
</template>

<script>
import {listClinic, getClinic, delClinic, addClinic, updateClinic, listClinicbyone} from "@/api/gaoxin/clinic";
import IconsDialog from "@/views/tool/build/IconsDialog";
import {listPatient, getPatient, insertPatient, updatePatient} from "@/api/gaoxin/patient";
import {getUserAll} from "@/api/system/user";
import {listTaskalive} from "@/api/gaoxin/taskdata";
import dayjs from "@/api/gaoxin/dayjs.min";
import Recorder from "js-audio-recorder";

export default {
  name: "Clinic",
  components: {IconsDialog},
  dicts: ['disease','marital_status', 'clinic_status', 'patient_source','patient_status', 'disease', 'department', 'ward', 'sys_user_sex'],
  data() {
    return {
      vloading: false,
      ocrsen: '',
      asrsen: '',
      recorder: null,
      playTime: 0,
      timer: null,
      recorderFlag: false,
      open0: false,
      open1: false,
      userOptions:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 患者总条数
      ptotal: 0,
      // 就诊信息表格数据
      clinicList: [],
      // 患者列表信息表格数据
      patientList: [],
      // 弹出层标题
      title: "",
      // 患者列表弹出层标题
      patientTitle: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层
      vis: false,
      // pane
      activeName: "1",
      //患者下的任务是否都已审核
      isActive:true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        source: null,
        preDiagnose: null,
        manageId: null,
        firstDoctorId: null,
        secondDoctorId: null,
        illnessSummary: null,
        preHistory: null,
        familyHistory: null,
        disease: null,
        department: null,
        ward: null,
        bedNum: null,
        createTime: null,
        outTime: null,
        patientId: null,
        status: null
      },
      // 查询参数
      queryPatientParams: {
        pageNum: 1,
        pageSize: 10,
        patientNo: null,
        patientName: null,
        patientBirthday: null,
        patientAge: null,
        patientGender: null,
        patientIdentityNo: null,
        patientJob: null,
        patientWeight: null,
        patientHeight: null,
        patientFolk: null,
        patientAddress: null,
        patientPhone: null,
        patientMarriage: null,
        patientStatus: null,
      },
      Form: {},
      // 表单参数
      form: {},
      // 表单参数
      patientForm: {
        patientBirthday: ''
      },
      // 表单校验
      patientrules: {
        patientName: [
          {required: true, message: "患者名称不能为空", trigger: "blur"},
        ],
        patientIdentityNo: [
          {required: true, message: '身份证不能为空', trigger: "blur"},
          {pattern:/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur'}
        ],
        patientPhone: [
          {required: true, message: "患者联系方式不能为空", trigger: "blur"},
          {pattern:/^1\d{10}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$/, message: "请输入正确的联系方式(固话加区号)", trigger: "blur"}
        ]
      },
      clinicrules: {
        source: [
          {required: true, message: "患者来源 不能为空", trigger: "blur"},
        ]
      }
    };
  },
  created() {
    this.getListbyone();
    this.getInfo();
  },
  watch: {
    'patientForm.patientBirthday': {
      handler: function (newVal, oldVal) {
        console.log(newVal, oldVal);
        if(newVal != '') {
          var birthdays = new Date(newVal.replace(/-/g, "/"));
          var d = new Date();
          var age =
            d.getFullYear() -
            birthdays.getFullYear() -
            (d.getMonth() < birthdays.getMonth() ||
            (d.getMonth() == birthdays.getMonth() &&
              d.getDate() < birthdays.getDate())
              ? 1
              : 0);
          this.patientForm.patientAge = age;
        }

      },
      deep: true
    }
  },
  methods: {

    handleClose() {
    },
    uploadFile(params) {
      // this.startLoading();
      this.vloading = true;
      // console.log(document.querySelector("#inputArea"));
      const formData = new FormData()
      formData.append('file', params.file)
      const axios = require('axios')
      axios.post("http://127.0.0.1:5000/uploadOcr", formData).then(res => {
        this.ocrsen = res.data;
        // console.log(res);
        // this.endLoading();
        this.vloading = false;
      })

    },
    // 开始录音
    startRecorder() {
      this.recorderFlag = true;
      this.recorder = new Recorder({
        sampleBits: 16, // 采样位数，支持 8 或 16，默认是16
        sampleRate: 16000, // 采样率，支持 11025、16000、22050、24000、44100、48000，根据浏览器默认值，我的chrome是48000
        numChannels: 1, // 声道，支持 1 或 2， 默认是1
      })
      // 绑定事件-打印的是当前录音数据
      this.recorder.onprogress = function (params) {
        // console.log('--------------START---------------')
        // console.log('录音时长(秒)', params.duration);
        // console.log('录音大小(字节)', params.fileSize);
        // console.log('录音音量百分比(%)', params.vol);
        // console.log('当前录音的总数据([DataView, DataView...])', params.data);
        // console.log('--------------END---------------')
      }
      this.recorder.start().then(() => {
      }, (error) => {
        // 出错了
        console.log(`${error.name} : ${error.message}`);
      });
    },
    // 继续录音
    resumeRecorder() {
      this.recorder.resume()
    },
    // 暂停录音
    pauseRecorder() {
      this.recorder.pause();
    },
    // 结束录音
    stopRecorder() {
      this.recorder.stop()
    },
    // 录音播放
    playRecorder() {
      if (this.recorderFlag === false) {
        this.$message.error({
          message: '请先录制语音！',
          center: true
        });
      }
      else {
        this.recorder.play();
        // 播放时长
        this.timer = setInterval(() => {
          try {
            this.playTime = this.recorder.getPlayTime()
          } catch (error) {
            this.timer = null
          }
        }, 100)
      }
    },
    // 暂停录音播放
    pausePlayRecorder() {
      if (this.recorderFlag === false) {
        this.$message.error({
          message: '请先录制语音！',
          center: true
        });
      }
      else {
        this.recorder.pausePlay();
      }
    },
    // 恢复录音播放
    resumePlayRecorder() {
      if (this.recorderFlag === false) {
        this.$message.error({
          message: '请先录制语音！',
          center: true
        });
      }
      else {
        this.recorder.resumePlay();
      }
    },
    // 停止录音播放
    stopPlayRecorder() {
      if (this.recorderFlag === false) {
        this.$message.error({
          message: '请先录制语音！',
          center: true
        });
      }
      else {
        this.recorder.stopPlay();
      }
    },
    // 销毁录音
    destroyRecorder() {
      if (this.recorderFlag === false) {
        this.$message.error({
          message: '请先录制语音！',
          center: true
        });
      }
      else {
        this.recorderFlag = false;
        this.recorder.destroy();
      }
    },
    // 上传语音识别
    asrRecorder() {
      if (this.recorderFlag) {
        this.vloading=true;
        const formData = new FormData()
        const blob = this.recorder.getPCMBlob();//获取 PCM 数据
        const newbolb = new Blob([blob], {type: 'audio/pcm'})
        const fileOfBlob = new File([newbolb], '录音文件' + '.pcm')
        formData.append('file', fileOfBlob)
        const axios = require('axios')
        axios.post("http://127.0.0.1:5000/uploadAsr", formData).then(res => {
          console.log(res)
          this.asrsen=res.data;
          this.vloading=false;
        })
      } else {
        this.$message.error({
          message: '请先录制语音！',
          center: true
        });
      }
    },
    // 获取麦克风权限
    getPermission() {
      Recorder.getPermission().then(() => {
        this.$Message.success('获取权限成功')
      }, (error) => {
        console.log(`${error.name} : ${error.message}`);
      });
    },
    // 打开文字识别弹窗
    handleOCR() {
      this.open0 = true;
    },
    // 打开语音识别弹窗
    handleSpeech() {
      this.open1 = true;
    },
    // 关闭识别弹窗
    cancelDialog() {
      this.open0 = false;
      this.open1 = false;
    },

    getInfo() {
      getUserAll().then(response => {
        this.userOptions = response.users;
        console.log('userOptions',this.userOptions)
      });
    },
    importpat() {
      var temp = this.patientForm.patientIdentityNo;
      if (temp === undefined || temp === null || temp === "") {
        this.$message('输入身份证后才可以导入患者基本信息');
        return;
      }
      listPatient({
        patientIdentityNo: temp,
      }).then(response => {
        console.log(response.rows);
        if (response.rows[0]) {
          this.patientForm = response.rows[0]
        } else {
          this.$message('身份证号码不存在');
          this.resetForm('patientForm')
        }
      });
    },
    // 转到相关任务列表
    totasks(row) {
      // console.log('row',row)
      this.$tab.closeOpenPage({
        path: '/taskdata', query: {
          data: row,
        }
      })
    },
    handleStatusChange(row) {
      let clinicId=row.clinicId
      listTaskalive({clinicId:clinicId}).then(response=>{
        let taskList = response.rows;
        // console.log('taskList',taskList)
        for(let i=0;i<taskList.length;i++){
          if(taskList[i].status<3){
            this.isActive=false
            break
          }
        }
        if(!this.isActive){
          this.$alert('该患者仍有任务未审核，无法出院', '提示', {
            confirmButtonText: '确定',
            callback: action => {
              this.$message({
                type: 'info',
                message: `已取消出院`
              });
            }
          });
        }else {
          this.$confirm('该患者的任务均已审核，确认出院吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            // console.log('status:',row.status)
            // row.status=!row.status
            // console.log('status:',row.status)
            row.status=1
            row.outTime = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')
            updateClinic(row).then(() => {
              this.$tab.refreshPage();
              this.$message({
                type: 'success',
                message: '该患者已出院!'
              });

            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消出院'
            });
          })
        }
      })

    },
    /** 查询就诊信息列表 */
    getListbyone() {
      this.loading = true;
      listClinicbyone(this.queryParams).then(response => {
        this.clinicList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询就诊信息列表 */
    getList() {
      this.loading = true;
      listClinic(this.queryParams).then(response => {
        this.clinicList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询患者列表 */
    getPatientList() {
      this.loading = true;
      this.vis = true;
      this.patientTitle = '患者列表';
      this.queryPatientParams.patientIdentityNo = null;
      listPatient(this.queryPatientParams).then(response => {
        this.patientList = response.rows;
        this.ptotal = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.activeName = "1";
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        clinicId: null,
        source: null,
        preDiagnose: null,
        manageId: null,
        firstDoctorId: null,
        secondDoctorId: null,
        illnessSummary: null,
        preHistory: null,
        familyHistory: null,
        disease: null,
        department: null,
        ward: null,
        bedNum: null,
        createTime: null,
        outTime: null,
        patientId: null,
        status: "0"
      };
      this.resetForm("form");
    },
    patientReset() {
      this.patientForm = {
        patientId: null,
        patientNo: null,
        patientName: null,
        patientBirthday: '',
        patientAge: null,
        patientGender: null,
        patientIdentityNo: null,
        patientJob: null,
        patientWeight: null,
        patientHeight: null,
        patientFolk: null,
        patientAddress: null,
        patientPhone: null,
        patientMarriage: null,
        patientStatus: null,
      };
      this.resetForm("patientForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    patientQuery() {
      this.queryPatientParams.pageNum = 1;
      this.getPatientList();
    },
    /** 重置按钮操作 */
    patientResetQuery() {
      this.resetForm("queryPatientParams");
      this.patientQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.clinicId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.patientReset();
      this.title = "添加就诊信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.patientReset();
      const clinicId = row.clinicId || this.ids
      getClinic(clinicId).then(response => {
        this.form = response.data;
        const patientId = this.form.patientId;
        this.open = true;
        this.title = "修改就诊信息";
        getPatient(patientId).then(response => {
          this.patientForm = response.data;
        });
      });

    },
    handleSelect(row) {
      this.vis = false;
      this.form.patientId = row.patientId;
      getPatient(row.patientId).then(response => {
        this.patientForm = response.data
        console.log(response.data)
      })
    },
    assignment(id) {
      this.form.patientId = id;
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    charge1() {
      this.activeName="1";
    },
    charge2() {
      this.activeName="2";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["patientForm"].validate(valid => {
        if(valid){
          this.$refs["form"].validate(valid => {
            if (valid) {
              if(this.patientForm.patientNo == null) {
                const identityNo = this.patientForm.patientIdentityNo;
                this.queryPatientParams.patientIdentityNo = identityNo;
                listPatient(this.queryPatientParams).then(response => {
                  this.patientList = response.rows;
                  this.ptotal = response.total;
                });
                if(this.ptotal === 0) {
                  insertPatient(this.patientForm).then(response => {
                    this.$modal.msgSuccess("操作成功");
                    var patientId = response.patientId;
                    // console.log("patientId=" + patientId)
                    this.patientForm.patientId = patientId;
                    this.form.patientId = patientId;
                    // console.log(this.form.patientId);
                    // console.log(this.patientForm.patientId)
                    addClinic(this.form).then(response => {
                      this.$modal.msgSuccess("操作成功");
                      // this.open = false;
                      this.getListbyone();
                    });
                    this.open = false;
                  });
                } else {
                  this.$modal.msgError("操作失败，该患者已存在");
                }
              } else {
                // console.log(this.form.patientId);
                // console.log(this.patientForm.patientId)
                if (this.form.clinicId != null) {

                  updateClinic(this.form).then(response => {

                    updatePatient(this.patientForm).then(response => {
                      console.log("123");
                    });
                    this.$modal.msgSuccess("操作成功");
                    console.log("123");
                    this.getListbyone();
                  });
                  this.open = false;
                } else {
                  addClinic(this.form).then(response => {
                    this.$modal.msgSuccess("操作成功");
                    // this.open = false;
                    this.getListbyone();
                  });
                  this.open = false;
                }
              }

            }
          })
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const clinicIds = row.clinicId || this.ids;
      this.$modal.confirm('是否确认删除就诊信息编号为"' + clinicIds + '"的数据项，以及相关的任务数据？删除后无法恢复！')
        .then(function () {
          return delClinic(clinicIds);
        }).then(() => {
        this.getListbyone();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/clinic/export', {
        ...this.queryParams
      }, `clinic_${new Date().getTime()}.xlsx`)
    },
  }
};
</script>
<style>
</style>
